package cn.itsource.hrm.web.controller;


import cn.itsource.course.doc.CourseDoc;
import cn.itsource.course.query.CourseQuery;
import cn.itsource.hrm.repostory.CourseRepostory;
import cn.itsource.util.AjaxResult;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/es")

public class CourseController {
    @Autowired
    private CourseRepostory courseRepostory;

    @PostMapping("/save")
    public AjaxResult save(@RequestBody CourseDoc courseDoc) {
        courseRepostory.save(courseDoc);
        return AjaxResult.me();
    }

    @RequestMapping("/delete/{id}")
    public AjaxResult delete(@PathVariable("id") Long id) {
        courseRepostory.deleteById(id);
        return AjaxResult.me();
    }

    //查询+过滤
    @RequestMapping("/seach")
    public List<CourseDoc> seach(@RequestBody CourseQuery courseQuery) {
        Integer page1 = courseQuery.getPage();
        Integer rows = courseQuery.getRows();
        //查询
        //.......................
        //创建查询条件
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //分页查询条件设置（这里的java代码页数从0开始）
        nativeSearchQueryBuilder.withPageable(PageRequest.of((page1 - 1), rows));
        String sortField = courseQuery.getSortField();
        String sortType = courseQuery.getSortType();
        SortOrder order = null;
        if (sortField == null || sortType == null) {
            sortField = "price";
            order = SortOrder.DESC;
        } else {
            if (sortType.equals("desc")) {
                order = SortOrder.DESC;
            } else {
                order = SortOrder.ASC;
            }
            //将排序的字段全部转化成小写，前端传过来的就是小写，也是为了方便统一
            switch (sortField.toLowerCase()) {
                case "xl":
                    sortField = "buyCount";
                    break;
                case "xp":
                    sortField = "onlineDate";
                    break;
                case "jg":
                    sortField = "price";
                    break;
                case "rq":
                    sortField = "viewCount";
                    break;
                case "pl":
                    sortField = "comment";
                    break;
                default:
                    sortField = "price";
            }
        }
        //设置排序,chrl+0 在FieldSortBuilder查询该类以及父类的方法
        FieldSortBuilder fieldSortBuilder = new FieldSortBuilder(sortField).order(order);
        nativeSearchQueryBuilder.withSort(fieldSortBuilder);

        //.....................................
        //过滤
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        List<QueryBuilder> must = boolQueryBuilder.must();
        String keyword = courseQuery.getKeyword();
        if (org.springframework.util.StringUtils.hasLength(keyword)) {
            //matchQuery 要分词  termQuery：不会分词 相当于模糊查询 must 为必须满足
            must.add(QueryBuilders.matchQuery("name", keyword));
        }
        Long priceMax = courseQuery.getPriceMax();
        Long priceMin = courseQuery.getPriceMin();
        //必须满足的条件
        List<QueryBuilder> list = boolQueryBuilder.filter();
        if (priceMax != null && priceMin != null) {
            //gte:大于等于1  lte：小于等于
            list.add(QueryBuilders.rangeQuery("price").gte(priceMin).lte(priceMax));
        }
        String productType = courseQuery.getProductType();
        if (StringUtils.hasLength(productType)) {
            list.add(QueryBuilders.termQuery("courseTypeId", productType));
        }
        nativeSearchQueryBuilder.withQuery(boolQueryBuilder);

        NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();

        Page<CourseDoc> page = courseRepostory.search(searchQuery);
        page.forEach(e -> {
            System.out.println(e);
        });
        //得到查询的总页数
        int totalPages = page.getTotalPages();
       // System.out.println(totalPages);
        //查询的总条数
        long totalElements = page.getTotalElements();
      //  System.out.println(totalElements);
        List<CourseDoc> content = page.getContent();
        return content;
    }
}



